package la.bbs558.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static la.bbs558.util.IpUtil.getIp;


/**
 * 功能描述：拦截器，验证token是否合法
 *
 */
@Component
@Slf4j
public class WebInterceptor implements HandlerInterceptor {
    /**
     * @param request
     * @param response
     * @param handler
     * @return boolean
     * @Description 鉴权
     * @author bbs558
     * @date 2021/7/14 11:39 上午
     */
    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
        String uri = request.getRequestURI();
        String method = request.getMethod();
        String ipAddress = getIp(request);
        log.info("请求:{}=>{}=>{}", ipAddress,method,uri);
        RequestThreadLocal.isMobileApp.set(isMobileApp(request));
        return true;
    }

    /**
     * 功能描述:每次请求结束，就销毁后台登录用户的ThreadLocal（防止ThreadLocal内存泄漏）
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     **/
    @Override
    public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, Exception ex) throws Exception {
        RequestThreadLocal.isMobileApp.remove();
    }

    private boolean isMobileApp(HttpServletRequest request) {
        return "uniapp".equals(request.getHeader("User-Agent"));
    }

}
